package com.atguigu.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.atguigu.commonutils.R;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantYmlUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.net.www.content.image.png;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {


    @Override
    public String upLoadFile(MultipartFile file) {

        String endPoint = ConstantYmlUtils.END_POINT;
        String accessKeyId = ConstantYmlUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantYmlUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantYmlUtils.BUCKET_NAME;

        try {
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
//            FileInputStream inputStream = new FileInputStream("D:\\Worker\\项目\\logos.png");

            System.out.println("Multi file: " +file);
            //获取文件流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String fileName = file.getOriginalFilename();

            String uuid = UUID.randomUUID().toString().replaceAll("-", "");

            fileName = uuid+ fileName;
            //获取当前日期
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = datePath + "/" + fileName;

            PutObjectResult putObjectResult = ossClient.putObject(bucketName, fileName, inputStream);

//            https://common-service-bucket.oss-cn-hangzhou.aliyuncs.com/logos.png

            String url = "https://" + bucketName + "." + endPoint + "/" + fileName;

            ossClient.shutdown();
            return  url;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }


}
